<template>
  <a-drawer
    :visible="visible"
    :title="title"
    placement="right"
    @close="cancelClick"
    width="500"
    :body-style="{
      height: 'calc(100% - 100px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
    destroyOnClose
  >
    <a-form layout="vertical">
      <a-form-item label="抬头类型" v-bind="validateInfos.title_type">
        <a-radio-group
          v-model:value="modelRef.title_type"
          name="radioGroup"
          @change="changeTitleType"
        >
          <a-radio :value="1">企业</a-radio>
          <a-radio :value="0">个人</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="纳税人资质" v-bind="validateInfos.company_type">
        <a-radio-group
          v-model:value="modelRef.company_type"
          name="radioGroup"
          @change="companyTypeChange"
        >
          <a-radio :value="0" v-if="modelRef.title_type == 1">
            一般纳税人
          </a-radio>
          <a-radio :value="1">小规模纳税人</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="默认发票类型"
        v-bind="validateInfos.default_invoice_type"
      >
        <a-select
          ref="select"
          v-model:value="modelRef.default_invoice_type"
          :getPopupContainer="(triggerNode) => triggerNode?.parentNode"
          placeholder="请选择默认发票类型"
        >
          <a-select-option :value="1">增值税普通发票</a-select-option>
          <a-select-option :value="2" v-if="modelRef.company_type == 0"
            >增值税专用发票</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item label="发票抬头" v-bind="validateInfos.title">
        <a-input v-model:value="modelRef.title" placeholder="请输入发票抬头" />
      </a-form-item>
      <template v-if="modelRef.title_type == 1">
        <a-form-item label="纳税人识别号" v-bind="validateInfos.tax_number">
          <a-input
            v-model:value="modelRef.tax_number"
            placeholder="请输入纳税人识别号"
          />
        </a-form-item>
        <a-form-item
          label="基本开户账号"
          v-bind="validateInfos.tax_bank_account"
        >
          <a-input
            v-model:value="modelRef.tax_bank_account"
            placeholder="请输入基本开户账号"
          />
        </a-form-item>
        <a-form-item label="基本开户银行" v-bind="validateInfos.tax_bank_name">
          <a-input
            v-model:value="modelRef.tax_bank_name"
            placeholder="请输入基本开户银行"
          />
        </a-form-item>
        <a-form-item
          label="企业注册地址"
          v-bind="validateInfos.tax_company_address"
        >
          <a-textarea
            v-model:value="modelRef.tax_company_address"
            placeholder="请输入企业注册地址"
            :rows="4"
          />
        </a-form-item>
        <a-form-item
          label="企业注册电话"
          v-bind="validateInfos.tax_company_tel"
        >
          <a-input
            v-model:value="modelRef.tax_company_tel"
            placeholder="请输入企业注册电话"
          />
        </a-form-item>
      </template>
      <a-form-item v-bind="validateInfos.is_default">
        <template #label>
          是否为<span> {{ $L("租客") }}</span
          >默认发票
        </template>
        <a-select
          ref="select"
          v-model:value="modelRef.is_default"
          :placeholder="defaultPlaceholder"
        >
          <a-select-option :value="1">是</a-select-option>
          <a-select-option :value="0">否</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click="cancelClick">取消</a-button>
      <a-button type="primary" @click="submitClick" :loading="loading"
        >保存</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  ref,
  createVNode,
  onActivated,
  watch,
  computed,
  reactive,
  toRefs,
} from "vue";
import request from "@/common/utils/request";
import { useRoute, useRouter } from "vue-router";
import { Form, message } from "ant-design-vue";
const useForm = Form.useForm;
import BLCOMMON from "bl-common-vue3";

export default defineComponent({
  name: "AddInvoice",
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    detail: {
      type: Object,
      default: () => {
        return {};
      },
    },
    ownerId: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      count: 0,
      loading: false,
    });

    const defaultPlaceholder = computed(() => {
      return `请选择是否为${BLCOMMON.utils.L("租客")}默认发票`;
    });

    const modelRef = reactive({
      title_type: 1,
      company_type: 0,
      default_invoice_type: undefined,
      tax_company_tel: "",
      title: "",
      tax_number: "",
      tax_bank_account: "",
      tax_bank_name: "",
      tax_company_address: "",
      is_default: 0,
    });
    const rulesRef = reactive({
      title_type: [
        {
          required: true,
          message: "请选择抬头类型",
        },
      ],
      company_type: [
        {
          required: true,
          message: "请选择公司客户类型",
        },
      ],
      default_invoice_type: [
        {
          required: true,
          message: "请选择默认发票类型",
        },
      ],
      title: [
        {
          required: true,
          message: "请输入发票抬头",
        },
      ],
      tax_number: [
        {
          required: true,
          message: "请输入纳税人识别号",
        },
      ],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const companyTypeChange = ({ target }) => {
      if (target.value == 1) {
        setTimeout(() => {
          modelRef.default_invoice_type = 1;
        }, 10);
      }
    };

    const changeTitleType = () => {
      if (modelRef.title_type) {
        rulesRef.tax_number[0].required = true;
        modelRef.company_type = 0;
      } else {
        rulesRef.tax_number[0].required = false;
        modelRef.company_type = 1;
      }
    };

    const cancelClick = () => {
      resetFields();
      context.emit("closeChange");
    };

    const submitClick = () => {
      validate().then(() => {
        let params = {
          ...modelRef,
        };
        if (params.title_type == 0) {
          delete params.tax_number,
            delete params.tax_bank_account,
            delete params.tax_bank_name,
            delete params.tax_company_address,
            delete params.tax_company_tel;
        }
        params.owner_id = Number(route.query.id) || props.ownerId;
        state.loading = true;
        if (props.id) {
          params.id = props.id;
          request
            .put("/org", "/org/owner/invoice/title", { ...params })
            .then(() => {
              message.success("编辑成功");
              state.loading = false;
              resetFields();
              context.emit("successChange");
            })
            .catch(() => {
              state.loading = false;
            });
          return;
        }
        request
          .post("/org", "/org/owner/invoice/title", { ...params })
          .then(() => {
            message.success("保存成功");
            state.loading = false;
            resetFields();
            context.emit("successChange");
          })
          .catch(() => {
            state.loading = false;
          });
      });
    };

    const getnvoiceDetail = () => {
      request
        .get("/org", `/org/owner/invoice/title/${props.id}`)
        .then((res) => {
          setModelRef(res.detail);
        });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        if (key in modelRef) {
          modelRef[key] = state[key];
        }
      }
    };

    const title = computed(() => {
      return props.id ? "编辑开票" : "添加开票";
    });

    watch(
      () => modelRef.title_type,
      () => {
        if (props.visible) {
          changeTitleType();
        }
      }
    );

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          if (props.detail) {
            modelRef.title_type = props.detail.is_personal == 1 ? 0 : 1;
            modelRef.company_type = props.detail.is_personal == 1 ? 1 : 0;
          }
          if (props.id) {
            getnvoiceDetail();
          }
        }
      }
    );

    return {
      ...toRefs(state),
      title,
      cancelClick,
      submitClick,
      validateInfos,
      modelRef,
      changeTitleType,
      companyTypeChange,
      defaultPlaceholder,
    };
  },
});
</script>

<style lang="less" scoped></style>
